/**
 * 功能:订单 控制器类
 * 开发人员:daniel.yan
 * 创建时间:2012/4/22 12:09:13
 */
package com.towker.frame.controller.sell;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.oro.io.RegexFilenameFilter;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.core.util.StringUtil;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Customs;
import com.towker.frame.model.sell.Delivery;
import com.towker.frame.model.sell.Order;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.sys.User;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.sell.DeliveryService;
import com.towker.frame.service.sell.OrderService;
import com.towker.frame.service.sell.RefGoodsService;
import com.towker.frame.service.sys.user.UserService;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;

//TK_ORDERS
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/sell")
public class OrderController extends BaseController
{
	private OrderService service;
	private DeliveryService deliveryService;
	private UserService userService;
	private GoodsService goodsService;
	private CustomsService customsService;
	
	//业务对象注入
	public void setOrderService(OrderService service)
	{
		this.service = service;
	}

	public void setDeliveryService(DeliveryService deliveryService) {
		this.deliveryService = deliveryService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public void setCustomsService(CustomsService customsService) {
		this.customsService = customsService;
	}

	//添加
	@RequestMapping("/addOrder{viewName}")
	public ModelAndView addOrder(HttpServletResponse response, HttpServletRequest request, Order po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
//			List<User> customCodes = userService.getCustomCodes();
			Map map = new HashMap();
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			result.addObject("customCodes", customCodes);
			result.addObject("custom_code", UserShare.getCurrentCustomCode(request));
			result.addObject("loginUser", UserShare.getCurrentUser(request));
			result.setViewName("/manage/sell/addOrder.jsp");
		}
		else if ("2".equals(viewName))
		{
			MyRequest myRequest = new MyRequest(request);
			String goodsInfo = myRequest.getString("goodsInfo");
			po.setCreate_time(new Date());
			po.setUser_code(UserShare.getCurrentUserCode(request));
			po.setUser_id(new Integer(String.valueOf(UserShare.getCurrentUserId(request))));
			if (UserShare.getUserNature(request) ==1) {
				po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
				//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
			}
			
			PrintWriter writer = response.getWriter();
			po.setOrder_sn(service.getNewOrderSN());
			po.setStatus(0);
			try
			{
				service.add(po);
				processRefGoods(request, RefGoodsType.ORDER_GOODS, po.getId(), goodsInfo);
				writer.write("添加订单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加订单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delOrder")
	public void delOrder(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		Integer[] ids = CollectionUtil.toIntegerArray(req.getIntArray("keyIndex", 0));
		for (Integer id : ids) {
			service.delById(id);
			refGoodsService.deleteByInfoType(RefGoodsType.ORDER_GOODS.getValue(), id);
		}
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updOrder{viewName}")
	public ModelAndView updOrder(HttpServletRequest request, HttpServletResponse response, Order po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		PrintWriter writer = response.getWriter();
		if ("1,3,5,7,9".indexOf(viewName) > -1)
		{
			Integer id = req.getInt("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.ORDER_GOODS.getValue(), id));
			result.addObject("action", StringUtil.toInteger(viewName) + 1);
			//List<User> customCodes = userService.getCustomCodes();
			Map map = new HashMap();
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			result.addObject("customCodes", customCodes);
			result.addObject("custom_code", UserShare.getCurrentCustomCode(request));
			result.addObject("loginUser", UserShare.getCurrentUser(request));
			User cUser = userService.getById(po.getUser_id());
			if (cUser != null && new Integer(2).equals(cUser.getUserNature())) {
				result.addObject("userNature", 2);
			} else {
				result.addObject("userNature", 1);
			}
			result.setViewName("/manage/sell/updOrder.jsp");
		}
		else if ("2".equals(viewName))
		{
			String goodsInfo = req.getString("goodsInfo");
			Order oldOrder = service.getById(po.getId());
			try
			{
				oldOrder.setCustom_code(po.getCustom_code());
				oldOrder.setCreate_date(po.getCreate_date());
				oldOrder.setRemark(po.getRemark());
				service.update(oldOrder);
				processRefGoods(request, RefGoodsType.ORDER_GOODS, po.getId(), goodsInfo);
				writer.write("修改订单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改订单失败！" + e.getCause());
			}
		} else if ("4".equals(viewName)){
			//确认
			Order oldOrder = service.getById(po.getId());
			oldOrder.setBaojia_qr_date(po.getBaojia_qr_date());
			oldOrder.setBaojia_qr_time(new Date());
			oldOrder.setBaojia_qr_user_code(UserShare.getCurrentUserCode(request));
			oldOrder.setBaojia_qr_user_id(new Integer(String.valueOf(UserShare.getCurrentUserId(request))));
			oldOrder.setQr_remark(po.getQr_remark());
			oldOrder.setStatus(po.getStatus());
			if (oldOrder.getStatus() == 6) {
				service.update(oldOrder);
				writer.write("订单已成功取消!");
			} else {
				oldOrder.setStatus(3);
				service.update(oldOrder);
				writer.write("订单已成功确认!");
			}
		} else if ("6".equals(viewName)){
			String goodsInfo = req.getString("goodsInfo");
			//报价
			Order oldOrder = service.getById(po.getId());
			oldOrder.setBaojia_date(po.getBaojia_date());
			oldOrder.setBaojia_time(new Date());
			oldOrder.setBaojia_user_code(UserShare.getCurrentUserCode(request));
			oldOrder.setBaojia_user_id(new Integer(String.valueOf(UserShare.getCurrentUserId(request))));
			oldOrder.setBj_remark(po.getBj_remark());
			oldOrder.setStatus(2);
			service.update(oldOrder);
			processRefGoods(request, RefGoodsType.ORDER_GOODS, po.getId(), goodsInfo);
			writer.write("订单报价成功！");
		} else if ("8".equals(viewName)){
			//审核
			Order oldOrder = service.getById(po.getId());
			oldOrder.setBaojia_sh_date(po.getBaojia_sh_date());
			oldOrder.setBaojia_sh_time(new Date());
			oldOrder.setBaojia_sh_user_code(UserShare.getCurrentUserCode(request));
			oldOrder.setBaojia_sh_user_id(new Integer(String.valueOf(UserShare.getCurrentUserId(request))));
			oldOrder.setSh_remark(po.getSh_remark());
			oldOrder.setStatus(po.getStatus());
			if (oldOrder.getStatus()==7) {
				service.update(oldOrder);
				writer.write("订单审核不通过成功！");
			} else {
				oldOrder.setStatus(4);
				service.update(oldOrder);
				//审核通过后处理在下订单数量
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.ORDER_GOODS.getValue(), oldOrder.getId());
				for (RefGoods refGoods2 : refGoods) {
					goodsService.addDownOrderAmount(refGoods2.getGoods_id().longValue(), refGoods2.getAmount());
				}
				writer.write("订单审核成功！");
			}
		} else if ("10".equals(viewName)){
			//提交
			Order oldOrder = service.getById(po.getId());
			oldOrder.setSubmit_date(po.getSubmit_date());
			oldOrder.setSubmit_time(new Date());
			oldOrder.setRemark(po.getRemark());
			oldOrder.setStatus(1);
			service.update(oldOrder);
			writer.write("订单提交成功！");
		} /*else if ("11".equals(viewName)) {
			//复制到送货单
			Integer id = req.getInt("keyIndex");
			Order order = service.getById(id);
			order.setStatus(5);
			service.update(order);
			Delivery delivery = new Delivery();
			delivery.setDelivery_sn(deliveryService.getNewDeliverySN());
			delivery.setCustom_code(order.getCustom_code());
			delivery.setOrder_id(order.getId());
			delivery.setOrder_code(order.getOrder_sn());
			deliveryService.add(delivery);
			
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.ORDER_GOODS.getValue(), delivery.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(delivery.getId());
				refGoods2.setInfo_type(RefGoodsType.DELIVERIE_GOODS.getValue());
				refGoodsService.add(refGoods2);
			}
			writer.write("复制到送货单!");
		}*/
		return result;
	}

	//获得分页
	@RequestMapping("/getOrder")
	public ModelAndView getOrder(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//经销商或客户只能查询自己的订单
		if (UserShare.getUserNature(request) == 2) {
			map.put("auth_custom_code", UserShare.getCurrentCustomCode(request));
		} else {//公司员工只能查询当前登录用户所属公司及部门的订单
			map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
			//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		}
		PageModel<Order> pageModel = service.getPage(page, pageSize, map);
		for(int i=0;i<pageModel.getResult().size();i++){
			String code = pageModel.getResult().get(i).getCustom_code();
			pageModel.getResult().get(i).setCustoms_name(customsService.getCustomName(true, pageModel.getResult().get(i).getUser_id(), code));
		}
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.addObject("loginUser", UserShare.getCurrentUser(request));
		result.setViewName("/manage/sell/getOrder.jsp");
		return result;
	}

	//明细
	@RequestMapping("/getOrderById")
	public ModelAndView getOrderById(HttpServletRequest request, HttpServletResponse response)
	{
		Order po = null;
		MyRequest req = new MyRequest(request);
		Integer id = req.getInt("keyIndex");
		po = service.getById(id);
		po.setCustoms_name(customsService.getCustomName(true, po.getUser_id(), po.getCustom_code()));
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.ORDER_GOODS.getValue(), id));
		result.setViewName("/manage/sell/getOrderById.jsp");
		return result;
	}
}
